import {designPage, onMounted, reactive} from "@peryl/react-compose";
import {$notice, $previewer, createSimpleDate, i18n, Icon, Loading, PageCard, PageCardContent} from "plain-design";
import {usePageService} from "../../modules/micro/usePageService";
import {usePageConfig} from "../../micro/MicroApp.pageConfig";
import {useCmsEditorOption} from "../../modules/cms-visual-editor";
import {iResumeRecord} from "./resume.utils";
import {CmsEditor, PlainCmsNamespace} from "@peryl/react-cms-editor";
import {pathJoin} from "@peryl/utils/pathJoin";
import {deepcopy} from "@peryl/utils/deepcopy";
import {http} from "../../modules/plain-design/http";
import './resume-template-edit-page.scss';
import {exportElement2Pdf} from "./exportElement2Pdf";
import {saveResume} from "./saveResume";

export default designPage(() => {

  const { nav, pageParam } = usePageService();

  let sourceResumeRecord: iResumeRecord | undefined = pageParam.resume;

  usePageConfig(config => {config.hideNavigation = true;});

  const state = reactive({
    saving: false,            // 正在保存
    exportingImage: false,    // 正在导出图片
    exportingJson: false,     // 正在导出Json
    exportingPdf: false,      // 正在导出Pdf
  });

  const option = useCmsEditorOption({
    isRunning: false,
    defaultData: [],
    editorCacheKey: 'resume-template-designer',
    panelLeftWidth: 235,
    panelRightWidth: 330,
    enableParamVariablesForCmsEditor: true,
    defaultDesignWidth: 820,
  });

  option.panelOperation.registry(1, 'back', 'right', () => (
    <div className="cms-editor-panel-operation-button" onClick={() => {nav.back();}}>
      <span><Icon icon="pi-undo"/></span><span>{i18n.$it('base.back').d('返回')}</span>
    </div>
  ));

  option.panelOperation.registry(2, 'save', 'right', () => (
    <div className="cms-editor-panel-operation-button" onClick={() => {handler.save();}}>
      <span>{state.saving ? <Loading/> : <Icon icon="pi-save"/>}</span><span>{i18n.$it('base.edit.save').d('保存')}</span>
    </div>
  ));

  option.panelOperation.registry(20, 'exportImage', 'center', () => (
    <div className="cms-editor-panel-operation-button" onClick={() => {handler.exportImage();}}>
      <span>{state.exportingImage ? <Loading/> : <Icon icon="pi-image"/>}</span><span>{i18n.$intl('cms_external.exportImage').d('导出图片')}</span>
    </div>
  ));

  option.panelOperation.registry(21, 'exportJson', 'center', () => (
    <div className="cms-editor-panel-operation-button" onClick={() => {handler.exportJson();}}>
      <span>{state.exportingJson ? <Loading/> : <Icon icon="pi-file"/>}</span><span>{i18n.$intl('cms_external.exportJson').d('导出JSON')}</span>
    </div>
  ));

  option.panelOperation.registry(22, 'exportPdf', 'center', () => (
    <div className="cms-editor-panel-operation-button" onClick={() => {handler.exportPdf();}}>
      <span>{state.exportingPdf ? <Loading/> : <Icon icon="pi-file-pdf"/>}</span><span>{i18n.$intl('cms_external.exportPdf').d('导出PDF')}</span>
    </div>
  ));

  const handler = {
    save: async () => {
      await saveResume({
        onStart: () => {state.saving = true;},
        onFinally: () => {state.saving = false;},
        onSuccess: (newResumeRecord) => {sourceResumeRecord = newResumeRecord;},
        image: await option.methods.getSnapshot() ?? 'NO_IMAGE',
        dataMetas: option.state.getStateData(),
        sourceResumeRecord,
        isTemplate: 'Y'
      });
    },
    exportImage: async () => {
      state.exportingImage = true;
      try {
        const snapshot = await option.methods.getSnapshot();
        !!snapshot && await $previewer.preview(snapshot);
      } finally {
        state.exportingImage = false;
      }
    },
    exportJson: async () => {
      state.exportingJson = true;
      try {
        // @ts-ignore
        const fileSaver = (await import('file-saver')).default;
        const dataMetas = option.state.getStateData();
        const blob = new Blob([JSON.stringify(dataMetas)], { type: 'text/plain;charset=utf-8' });
        fileSaver(blob, `${createSimpleDate()['YYYY-MM-DD HH:mm:ss']}.json`);
      } finally {
        state.exportingJson = false;
      }
    },
    exportPdf: async () => {
      const cmsEditorPageElement = option.refs.el?.querySelector('.cms-editor-page') as HTMLElement | undefined;
      if (!cmsEditorPageElement) {
        $notice.error('Internal Error!');
        return;
      }
      state.exportingPdf = true;
      try {
        await exportElement2Pdf(cmsEditorPageElement);
      } finally {
        state.exportingPdf = false;
      }
    },
  };

  onMounted(async () => {

    const dataMetas: PlainCmsNamespace.iDataMeta[] | null = (() => {
      if (!sourceResumeRecord?.jsonString) {return null;}
      return JSON.parse(sourceResumeRecord.jsonString);
    })();

    console.log({ dataMetas });

    if (!dataMetas?.length) {
      const closeLoading = nav.loading();
      try {
        const resp = await fetch(pathJoin(__webpack_public_path__, 'resume/resume_template.json'));
        const data = await resp.json();
        option.methods.updateData(data);
      } catch (e: any) {
        console.error(e);
        $notice.error('加载模板数据失败！' + (e.message || JSON.stringify(e)));
      } finally {
        closeLoading();
      }
    } else {
      option.methods.updateData(dataMetas);
    }

  });

  return () => (
    <PageCard full>
      <PageCardContent full noPadding className="resume-template-edit-page">
        <CmsEditor option={option} size="small"/>
      </PageCardContent>
    </PageCard>
  );
});
